package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"user-app/models"
)

type UserController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type JsonP struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
}

func (c *UserController) Get() {}

func (c *UserController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	tel := c.GetString("tel")
	szaq := c.GetString("szaq")
	dj := c.GetString("dj")
	sfyq := c.GetString("sfyq")
	user := models.User{
		Name: name,
		Age:  age,
		Tel:  tel,
		Szaq: szaq,
		Dj:   dj,
		Sfyq: sfyq,
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *UserController) List() {
	var alluser = []models.User{}

	page, _ := c.GetInt("page")
	size := 5
	var count int64
	models.DB.Model(&models.User{}).Count(&count)
	Sumpage := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size

	err := models.DB.Order("age desc").Offset(offset).Limit(size).Find(&alluser).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "查询失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonP{
			Code:    200,
			Msg:     "查询成功",
			Data:    alluser,
			Page:    page,
			Size:    size,
			Count:   count,
			Sumpage: Sumpage,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *UserController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.User{}, id).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
